package iohelper

import (
	"encoding/binary"
	"io"
)

type WriteHelper struct {
	writer  io.Writer
	bits    []byte
	byteOrd binary.ByteOrder
}

func (w *WriteHelper) WriteByte(b byte) (int, error) {
	w.bits[0] = b
	return w.writer.Write(w.bits[:1])
}

func (w *WriteHelper) WriteUint16(i uint16) (int, error) {
	w.byteOrd.PutUint16(w.bits, i)
	return w.writer.Write(w.bits[:2])
}

func (w *WriteHelper) WriteUint32(i uint32) (int, error) {
	w.byteOrd.PutUint32(w.bits, i)
	return w.writer.Write(w.bits[:4])
}

func (w *WriteHelper) WriteUint64(i uint64) (int, error) {
	w.byteOrd.PutUint64(w.bits, i)
	return w.writer.Write(w.bits[:8])
}

func (w *WriteHelper) Write(p []byte) (n int, err error) {
	return w.writer.Write(p)
}

// 读取动态长度
func (w *WriteHelper) WriteDynLen(nlen uint64) (n int, err error) {
	return WriteDynLen(w, nlen)
}

// 读取动态长度
func (w *WriteHelper) WriteString(str string) (n int, err error) {
	l := len(str)
	n, err = w.WriteDynLen(uint64(l))
	if err != nil {
		return
	}
	l, err = w.Write([]byte(str))
	n += l
	return
}

func NewWriteHelper(writer io.Writer, byteOrd binary.ByteOrder) *WriteHelper {
	if byteOrd == nil {
		byteOrd = binary.LittleEndian
	}
	return &WriteHelper{writer: writer, byteOrd: byteOrd, bits: make([]byte, 8)}
}
